import {getSystemSize, getWindowHeightRpx} from "../../utils/system";
import {px2rpx} from "../../miniprogram_npm/lin-ui/utils/util";
import {Categories} from "../../models/categories";
import {SpuListType} from "../../core/enum";

Page({
    data: {
        segHeight: null,
        categoryies: null,
        defaultRootId: 2,
    },
    onGotoSearch() {
        wx.navigateTo({
            url: '/pages/search/index'
        })
    },
    onLoad: async function (options) {
        this.setDynamicSegmentHeight()
        this.initCategoryData()
    },
    async initCategoryData() {
        const categories = new Categories()
        this.data.categoryies = categories
        await categories.getAll()
        const roots = categories.getRoots()
        const defaultRoot = this.getDefaultRoot(roots)
        const currentSubs = categories.getSubs(defaultRoot.id)
        console.log('currentSubs', currentSubs)
        this.setData({
            roots,
            currentSubs,
            currentBannerImg: defaultRoot.img
        })
    },
    getDefaultRoot(roots) {
        let defaultRoot = roots.find(r => r.id === this.data.defaultRootId)
        if (!defaultRoot) {
            defaultRoot = roots[0]
        }
        return defaultRoot
    },
    onSegChange(event) {
        const rootId = event.detail.activeKey
        console.log(rootId)
        const currentSubs = this.data.categoryies.getSubs(rootId);
        const currentRoot = this.data.categoryies.getRoot(rootId)
        console.log(currentRoot, currentSubs)
        this.setData({
            currentSubs,
            currentBannerImg: currentRoot.img
        })
    },
    onJumpToSpuList(event) {
        console.log('点击', event)
        const cid = event.detail.cid
        wx.navigateTo({
            url: `/pages/spu-list/index?cid=${cid}&type=${SpuListType.SUB_CATEGORY}`
        })
    },
    async setDynamicSegmentHeight() {
        /**
         * 动态计算左侧高度
         */
        const windowHeight = await getWindowHeightRpx()
        const h = windowHeight - 60 - 20 - 2
        this.setData({
            segHeight: h
        })
    }
});